package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"time"
)

// 保存结果到文件
func writeToFile() {
	//fileName := "Magnet_" + fmt.Sprintf("%d", time.Now().Unix()) + ".csv"
	fileName := "Magnet.csv"
	fout, err := os.Create(fileName)
	if err != nil {
		// 文件创建失败
		fmt.Println(fileName + " create failed!")
	}
	defer fout.Close()
	fout.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM
	w := csv.NewWriter(fout)
	w.Write([]string{"哈希值", "磁力链接", "标题", "文件列表", "文件数量", "种子创建时间", "文件体积", "收录时间"})

	s, ok := <-result
	for ok {
		time.Sleep(50 * time.Millisecond)
		//fmt.Println(write, s.hash)
		w.Write([]string{s.hash, s.title, s.file, strconv.Itoa(s.fileNumber), strconv.FormatInt(s.time, 10), strconv.FormatInt(s.fileSize, 10), strconv.FormatInt(s.indexTime, 10)})
		s, ok = <-result
	}
	w.Flush()
	// 等待结果保存完成后通知进程退出
	clo <- true
}
